package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserMallBuyCount;

import java.sql.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserMallBuyCountImpl extends TempDataObjectDao<UserMallBuyCount> {

	public Map<Integer, UserMallBuyCount> getUserMallBuyCountMap(long userId) {
		Map<Integer, UserMallBuyCount> dataMap = new ConcurrentHashMap<>();
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "select * from t_u_mall_buy_count where userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setLong(1, userId);
			rs = call.executeQuery();
			while (rs.next()) {
				UserMallBuyCount data = parse(rs);
				dataMap.put(data.getMallId(), data);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return dataMap;
	}

	@Override
	protected boolean addData(UserMallBuyCount data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_mall_buy_count(userId,mallId,count,lastUpdateTime) VALUES(?,?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getMallId());
			call.setInt(i++, data.getCount());
			call.setLong(i++, data.getLastUpdateTime());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(UserMallBuyCount data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_mall_buy_count SET count=?,lastUpdateTime=? WHERE userId=? and mallId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setInt(i++, data.getCount());
			call.setLong(i++, data.getLastUpdateTime());
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getMallId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected UserMallBuyCount parseData(ResultSet rs) throws SQLException {
		UserMallBuyCount data = new UserMallBuyCount();
		data.setUserId(rs.getLong("userId"));
		data.setMallId(rs.getInt("mallId"));
		data.setCount(rs.getInt("count"));
		data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
		return data;
	}
}
